/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package cn.iocoder.yudao.framework.server.websocket;

import cn.iocoder.yudao.framework.common.GameServerUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.handlermapping.NettyWsChannelContext;
import cn.iocoder.yudao.framework.message.ServerResponse;
import cn.iocoder.yudao.module.infra.util.TraceIdUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 游戏网络通信编码Handler，负责处理向网络层发送消息之前，将消息序列化为ByteBuf
 *
 * @author 王广帅
 * @since 2021/5/30 19:12
 */
@Slf4j
public class WebSocketEncoderHandler extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        final String traceId = ctx.channel().attr(NettyWsChannelContext.TRACE_ID).get();
        if (msg instanceof ServerResponse) {
            try {
                TraceIdUtil.setTraceId(traceId);
                final String text = JsonUtils.toJsonString(msg);
                ctx.channel().writeAndFlush(new TextWebSocketFrame(text));
                promise.setSuccess();
                log.info("返回WebSocket消息给客户端, channelId = {}, text = {}",
                        GameServerUtil.getChannelId(ctx.channel()), text);
            } finally {
                TraceIdUtil.removeTraceId();
            }
        } else {
            super.write(ctx, msg, promise);
        }
    }
}
